package pap;

import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;

public class NamedThreadFactory implements ThreadFactory {

	// constants

	private static final AtomicInteger POOL_NUMBER = new AtomicInteger(1);

	// internal vars

	private final ThreadGroup group;
	private final AtomicInteger threadNumber = new AtomicInteger(1);
	private final String namePrefix;

	/**
	 * Creation of a ThreadFactory with the specified name.
	 * 
	 * @param namePrefix
	 */
	public NamedThreadFactory(String namePrefix) {

		this.group = Thread.currentThread().getThreadGroup();
		this.namePrefix = namePrefix + "(pool" + POOL_NUMBER.getAndIncrement()
				+ "-thread-";
	}

	/**
	 * Creation of a new thread.
	 */
	public Thread newThread(Runnable r) {
		Thread t = new Thread(this.group, r, this.namePrefix
				+ this.threadNumber.getAndIncrement() + ")", 0L);

		return t;
	}
}
